//
//  SLProjectDetailVC.swift
//  sulit-loan
//
//  Created by 王刚锋 on 2025/4/19.
//  Copyright © 2025 coolBoy. All rights reserved.
//

import UIKit
import DCURLRouter
import SwiftyJSON
import MBProgressHUD

class SLProjectDetailVC: SLTableVC<Any> {

    var dataArray:[JSON] = []
    var nextData:JSON?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.refreshAction()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "SulitLoan"
        setupUI()
    }
    lazy var agreementStack:UIStackView = {
        let v = UIStackView(arrangedSubviews: [agreementCheckbox, agreementLabel])
        v.spacing = 8
        v.alignment = .center
        v.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(v)
        v.snp.makeConstraints { make in
            make.top.equalTo(applyButton.snp.bottom).offset(6.5)
            make.centerX.equalToSuperview()
        }
        return v
    }()
    override func refreshData(isPullDown: Bool = true) {
        let mbp = MBProgressHUD.showMessage(message: "")
        SLHttpTool.AsyncReportData(path: "/satisfies/mane",params:["sources":self.id], target: self) { responseCall, success, msg, code in
            mbp.hide(animated: false)
            self.tableview.mj_header?.endRefreshing()
            if success{
                self.dataArray.removeAll()
                self.json = responseCall["wavelets"]
                self.headView.setModel(model: self.json!["doorstep"])
                self.applyButton.setTitle(self.json!["doorstep"]["civilizations"].stringValue, for: .normal)
                self.title = self.json!["doorstep"]["singularly"].stringValue
                
                self.agreementCheckbox.isSelected = true
                self.updateLoginButtonState()
                if self.json!["kosambi"]["himalayas"].stringValue.isEmpty{
                    self.agreementStack.isHidden = true
                }else{
                    let t = self.json!["kosambi"]["himalayas"].stringValue
                    let arr = t.components(separatedBy: "||")
                    let xy = arr.last ?? ""
                    let labelText = arr.joined(separator: "")
                    // 设置部分文本带下划线
                    let attributedString = NSMutableAttributedString(string: labelText)
                    let range = labelText.range(of: xy)
                    let startIndex = labelText.distance(from: labelText.startIndex, to: range!.lowerBound)
                     let length = range!.upperBound.utf16Offset(in: labelText) - range!.lowerBound.utf16Offset(in: labelText)
                    let rangeNs = NSRange(location: startIndex, length: length)

                    attributedString.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: rangeNs)
                    attributedString.addAttribute(.foregroundColor, value: rgba(hex: "#1608EC"), range: rangeNs)
                    
                    self.agreementLabel.attributedText = attributedString
                    self.agreementStack.isHidden = false
                    
                }
                
                self.nextData = self.json!["perch"]
                let arr = self.json!["spikes"].arrayValue
                for json in arr {
                    self.dataArray.append(json)
                }
                self.tableview.reloadData()
            }else{
                MBProgressHUD.showError(error: msg)
            }
        }

    }
    private func setupUI() {
        view.backgroundColor = .white
        self.tableview.mj_footer = nil
        self.tableview.bounces = false
        self.configAutoHeight(estimatedHeight: 44,autoPullDown: true,nibName: "SLMineCell")
        self.tableview.tableHeaderView = self.headView
        self.tableview.snp.remakeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(self.navigationView.snp.bottom)
            make.bottom.equalTo(self.applyButton.snp.top)
        }
        
    }
    lazy private var headView:SLProjectDetailHeadView = {
        let v = kLoadXib(xibName: "SLProjectDetailHeadView") as! SLProjectDetailHeadView
        v.frame = CGRect(x: 0, y: 0, width: DevConfig.width, height: devWidthRatio * 209)
        return v
    }()
    override func numberOfSections(in tableView: UITableView) -> Int {
        return dataArray.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SLMineCell", for: indexPath) as! SLMineCell
        cell.titleL.text = dataArray[indexPath.section]["himalayas"].stringValue
        cell.icon.setUrlImage(url:dataArray[indexPath.section]["lotiform"].stringValue,placeholder: IMAGE("icon1"))
        cell.selectionStyle = .none
        cell.setSelect(s: dataArray[indexPath.section]["arrows"].boolValue)
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 26
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let json = self.dataArray[indexPath.section] as! JSON
        self.pushDetail(json: json)
    }
    func pushDetail(json:JSON){
        var data = json
        let awards = data["arrows"].intValue
        if awards != 1 {
            data = self.nextData!
        }
        let title = data["himalayas"].stringValue
        let distinguish = data["distinguish"].stringValue
        if distinguish == "firsta"{//身份证
            let page = SLIdentificationVC(id: self.id)
            page.title = title
            self.navigationController?.pushViewController(page, animated: true)
        }else if distinguish == "firstb"{// 个人基本信息
            let page = SLInformationAddVC(id: self.id)
            page.addType = .base
            page.title = title
            self.navigationController?.pushViewController(page, animated: true)
        }else if distinguish == "firstc"{//工作信息
            let page = SLInformationAddVC(id: self.id)
            page.addType = .job
            page.title = title
            self.navigationController?.pushViewController(page, animated: true)

        }else if distinguish == "firstd"{//联系人
            let page = SLContactAddVC(id: self.id)
            page.title = title
            self.navigationController?.pushViewController(page, animated: true)
        }else if distinguish == "firste"{//绑卡
            let url = data["imitate"].stringValue
            jump(url: url)

        }
    }
    
    
    lazy var applyButton: UIButton = {
       let button = UIButton(type: .system)
       button.setTitle("Apply Now", for: .normal)
       button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
       button.setTitleColor(.white, for: .normal)
       button.backgroundColor = rgba(hex: "#1608EC")
 
       button.layer.cornerRadius = 22
//       button.isEnabled = false
        self.view.addSubview(button)
       button.addTarget(self, action: #selector(applyAction), for: .touchUpInside)
       button.translatesAutoresizingMaskIntoConstraints = false
        button.snp.makeConstraints { make in
            make.left.equalTo(47)
            make.right.equalTo(-47)
            make.height.equalTo(44)
            make.bottom.equalTo(-30-DevConfig.safe_bottom)
        }
       return button
      }()
    
    lazy var agreementCheckbox: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(IMAGE("signin_icon_select"), for: .normal)
        button.setImage(IMAGE("signin_icon_selected"), for: .selected)
//        button.tintColor =  rgba(hex: "#1608EC")
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(agreementCheckboxTapped), for: .touchUpInside)
        return button
       }()
       
    lazy var agreementLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = .black
        label.translatesAutoresizingMaskIntoConstraints = false

        // 添加点击手势
        label.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(agreementClick))
        label.addGestureRecognizer(tapGesture)

        return label
       }()
       
    @objc private func agreementCheckboxTapped() {
        agreementCheckbox.isSelected = !agreementCheckbox.isSelected
        updateLoginButtonState()
    }
    @objc private func applyAction(){
        if let data = self.nextData{
            let arrows = data["himalayas"].stringValue
            if !arrows.isEmpty{
                self.pushDetail(json: data)
                return
            }
        }
        if !agreementStack.isHidden,!agreementCheckbox.isSelected{return}
        var params:[String: String] = [:]
        params["translated"] = self.json!["doorstep"]["supporting"].stringValue
        params["darius"] = self.json!["doorstep"]["darius"].stringValue
        params["poles"] = self.json!["doorstep"]["effects"].arrayValue.first?.stringValue
        params["round"] = self.json!["doorstep"]["round"].stringValue
        MBProgressHUD.showMessage(message: "")
        SLHttpTool.AsyncReportData(path: "/satisfies/finish",params: params, target: self) { responseCall, success, msg, code in
          
            if success {
                self.navigationController?.popToRootViewController(animated: false)
                let applink = responseCall["wavelets"]["imitate"].stringValue
                jump(url: applink)
                SLHttpTool.AsyncUploadData(mahathat:"9",extended: self.json!["doorstep"]["supporting"].stringValue, thais: "", target: self) { responseCall, success, msg, code in
                    
                }
            }
        }
    }
    private func updateLoginButtonState() {
//        applyButton.isEnabled = agreementCheckbox.isSelected
        applyButton.backgroundColor = agreementCheckbox.isSelected ?  rgba(hex: "#1608EC") : rgba(hex: "#1608EC", a: 0.24)
    }
    @objc private func agreementClick(){
        let url = self.json!["kosambi"]["bird"].stringValue
        jump(url: url)
    }
}
